<template>
  <div class="upload-container">
    <el-button icon='el-icon-upload' size="mini" :style="{background:color,borderColor:color}"
               @click=" dialogVisible=true" type="primary">上传图片
    </el-button>
    <el-dialog append-to-body :visible.sync="dialogVisible">

      <!--
      <el-upload class="editor-slide-upload"
                 accept="image/jpeg,image/gif,image/png"
                 action="https://localhost:7890/api/img/add"
                 :headers="myHeaders"
                 :multiple="true"
                 :file-list="fileList"
                 :show-file-list="true"
                 list-type="picture-card"
                 :on-change="handleFileUploaderChange"
                 :on-remove="handleRemove"
                 :on-success="handleSuccess"
                 :before-upload="beforeUpload"
                 :auto-upload="false">

        -->

        <el-upload class="editor-slide-upload"
                 accept="image/jpeg,image/gif,image/png"
                 action="#"
                 :headers="myHeaders"
                 :multiple="true"
                
                 list-type="picture-card"
                 :on-change="handleFileUploaderChange"
                 :auto-upload="false">

        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script>
  import {get as getImage} from '@/api/image'
  import axios from 'axios'
  import {mapGetters} from 'vuex'
import { getToken } from '@/utils/auth'
  export default {
    name: 'editorSlideUpload',
    props: {
      color: {
        type: String,
        default: '#1890ff'
      }
    },
    data() {
      return {
       
        dialogVisible: false,
        listObj: [],
        fileList: [],
       
        myHeaders:{
           'content-type': 'multipart/form-data',
           "Authorization":getToken()  //token换成从缓存获取
        },
        token:getToken()
      }
    },
    computed:{
      ...mapGetters([
            'IMG_URL',
            
          ]),
    },
    methods: {
      handleFileUploaderChange(file){
               
                const self = this
                self.fileList.push(file)
              
              
      },

    
      handleSubmit() {
      
        let _self=this
       
        var param = new FormData();
      
        this.fileList.forEach(
            (val, index) => {
            
              param.append("file", val.raw);
            }
        );
        
        axios.post( process.env.BASE_API+"/img/add", param,{
          headers: {
           'content-type': 'multipart/form-data',
           "Authorization":getToken()  //token换成从缓存获取
         }
        }).then(response => {
            const res = response.data
            if (res.code !== 200) {
              Message({
                message: res.msg,
                type: 'error',
                duration: 3 * 1000
              })
            }else{
                let list = res.data.list;
                if (list===null) return
                _self.listObj=[]
               
                for (var i=0; i<list.length; i++)
                {     let imageInfo=list[i]
                      
                     
                      let url=this.IMG_URL + imageInfo.Imgid
                       _self.listObj.push ({"url":url});
                }
 
             
                this.$message({
                  type: 'success',
                  message: "上传成功！",
                  duration: 1000
                 });

                
                  this.$emit('successCBK', _self.listObj);
                  //this.listObj = [];
                  this.fileList = [];
                  this.dialogVisible = false;

            }

            
        });

      


      },
      handleSuccess(response, file) {
        console.log("handleSuccess")
        /*
        const uid = file.uid;
        const objKeyArr = Object.keys(this.listObj)
        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            this.listObj[objKeyArr[i]].url = this.dataObj.host + '/' + this.dataObj.path ;
            this.listObj[objKeyArr[i]].hasSuccess = true;
            return
          }
        }*/
      },
      handleRemove(file) {
        console.log("handleRemove")
        /*
        const uid = file.uid;
        const objKeyArr = Object.keys(this.listObj);
        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            delete this.listObj[objKeyArr[i]];
            return
          }
        }*/
      },
      beforeUpload(file) {
        console.log("beforeupload")
        /*
        const _self = this
        const fileName = file.uid;
        this.fileList.push(file)
        this.listObj[fileName] = {};
       
        console.log(this.listObj)
        return 
        let params={}
        //params['id']="0f4bc32b0f52f7cfb7d19305a6517724"
        return new Promise((resolve, reject) => {
          getImage(params).then(response => {
            
            _self.dataObj.key = response.data.path + '/${filename}';
            _self.dataObj.path = response.data.path;
            _self.dataObj.host = response.data.host;
            _self.listObj[fileName] = {hasSuccess: false, uid: file.uid, width: this.width, height: this.height};
            resolve(true)
          }).catch(err => {
            console.log(err)
            reject(false)
          })
        })*/
      } //
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .upload-container .editor-slide-upload{
    margin-bottom: 20px;
  }
</style>
